package org.chengyi.model_shop.service.impl;

import org.chengyi.model_shop.entity.User;
import org.chengyi.model_shop.mapper.OrderMapper;
import org.chengyi.model_shop.mapper.UserMapper;
import org.chengyi.model_shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Override
    public List<User> getUserList() {
        return userMapper.getUserList();
    }

    @Override
    public List<User> getUserListByUsername(String username) {
        if (username == null || username.equals("")) {
            return userMapper.getUserList();
        }
        return userMapper.getUserListByUsername(username);
    }
    @Override
    public String deleteUser(Integer id) {
        int count = orderMapper.countOrderByUserId(id);
        if (count > 0) {
            return "该用户有关联订单，无法删除";
        }
        // 没有关联订单才允许删除
        return userMapper.deleteUser(id) > 0 ? "删除成功" : "删除失败";
    }

    @Override
    public int updateUser(User user) {
        if (user.getPassword() != null) {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        return userMapper.updateUser(user);
    }


}
